angular.module('dt-picker', [])

.service 'dtPickerSrv', ($q, $compile, $rootScope, $http, $ionicBody, $ionicBackdrop, $ionicPopup, $ionicLoading) ->
    show: ->
        defer = $q.defer() # 用于返回给调用者

        $ionicBackdrop.retain() # 背景遮照
        $ionicLoading.show()

        showUI = (days) ->
            scope = $rootScope.$new()

            scope.defer = $q.defer() # 传递到directive中
            scope.days  = days

            template = '''
                <dt-picker-item q="defer" days="days"></dt-picker-item>
                '''
            linkFn = $compile template
            element = linkFn scope

            $ionicBody.get().appendChild element[0]
            scope.defer.promise.then ((dtData) -> # 从directive成功返回
                element.remove()
                $ionicBackdrop.release() # 取消背景遮照
                defer.resolve(dtData)
            ), ->
                element.remove()
                $ionicBackdrop.release() # 取消背景遮照
                defer.reject()

        showError = (msg) ->
            alertPopup = $ionicPopup.alert {title: '加载日期时间出错', template: msg}
            alertPopup.then (res) ->
                $ionicBackdrop.release() # 取消背景遮照
                defer.reject()

        # 延时1秒发出请求，保证至少显示1秒加载动画,避免动画突然闪现又消失
        _.delay (->
            $http.get '/customer/avaliable'
            .success (resp) ->
                $ionicLoading.hide()
                if resp.status == 0 and resp.body.length > 0
                    showUI resp.body
                else
                    showError resp.error
            .error ->
                $ionicLoading.hide()
                showError '您的网络又调皮了'
        ), 1000

        defer.promise # 返回promise给调用者

# 不要直接使用这个directive，而是使用上面的dtPickerService封装
.directive 'dtPickerItem', ($ionicScrollDelegate) ->
    restrict    : 'E'
    templateUrl : 'templates/util/dt-picker.html'
    scope:
        'defer' : '=q'      # 从dtPickerSrv获取defer
        'days'  : '=days'   # 同上
    link: ($scope, $element, $attrs) ->
        containerWidth = 81
        findEnableTime = (times) ->
            _.findIndex times, (time) -> time.status == 'enable'
        angular.extend $scope,
            activeDateIdx: 0 # 默认第一个日期为选中
            activeTimeIdx: undefined
            clickDate: (index) ->
                $scope.activeDateIdx = index
                $scope.activeTimeIdx = findEnableTime $scope.days[index].times
            clickTime: (index) ->
                if $scope.days[$scope.activeDateIdx].times[index].status == 'enable'
                    $scope.activeTimeIdx = index
            prevDate: ->
                datePicker = _.find $ionicScrollDelegate._instances, (s) -> s.$$delegateHandle == "date-picker"
                left = datePicker.getScrollPosition().left
                remain = left % containerWidth
                if remain > 0
                    left = left - remain
                else
                    left = left - containerWidth
                datePicker.scrollTo left, 0, true
            nextDate: ->
                datePicker = _.find $ionicScrollDelegate._instances, (s) -> s.$$delegateHandle == "date-picker"
                left = datePicker.getScrollPosition().left
                remain = left % containerWidth
                left = left + containerWidth
                if remain > 0
                    left = left - remain
                datePicker.scrollTo left, 0, true
            cancel: ->
                $scope.defer.reject()
            ok: ->
                if $scope.activeDateIdx >= 0 and $scope.activeTimeIdx >= 0
                    $scope.defer.resolve
                        date: $scope.days[$scope.activeDateIdx]
                        time: $scope.days[$scope.activeDateIdx].times[$scope.activeTimeIdx]
        $scope.activeTimeIdx = findEnableTime $scope.days[0].times
